package com.example.myapplication.mcamera;

import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import com.example.myapplication.R;
import com.example.myapplication.base.BaseActivity;
import com.molichuxing.baselibrary.utils.ImageTools;
import com.molichuxing.baselibrary.utils.Tip;

import java.io.File;
import java.io.IOException;

import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;

public class CameraVideoActivity extends BaseActivity {

    private Camera mCamera;
    private CameraPreview mPreview;

    private MediaRecorder mMediaRecorder;
    private boolean isRecording = false;

    private Button captureButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_video);

        // 创建Camera实例
        mCamera = getCameraInstance();

        // 创建预览视图，并作为Activity的内容
        mPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = findViewById(R.id.camera_preview);
        preview.addView(mPreview);

        addOnClickVideo();
    }

    /**
     * Add a listener to the Capture button
     */
    private void addOnClickVideo() {
        captureButton = findViewById(R.id.button_capture);
        captureButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isRecording) {
                            // stop recording and release camera
                            mMediaRecorder.stop();  // stop the recording
                            releaseMediaRecorder(); // release the MediaRecorder object
                            mCamera.lock();         // take camera access back from MediaRecorder

                            // inform the user that recording has stopped
                            setCaptureButtonText("Capture");
                            isRecording = false;
                        } else {
                            // initialize video camera
                            if (prepareVideoRecorder()) {
                                // Camera is available and unlocked, MediaRecorder is prepared,
                                // now you can start recording
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mMediaRecorder.start();
                                    }
                                }).start();

                                // inform the user that recording has started
                                setCaptureButtonText("Stop");
                                isRecording = true;
                            } else {
                                // prepare didn't work, release the camera
                                releaseMediaRecorder();
                                // inform user
                            }
                        }
                    }
                }
        );
    }

    /**
     * 按钮动态更改
     *
     * @param capture
     */
    private void setCaptureButtonText(String capture) {
        captureButton.setText(capture);
    }

    private boolean prepareVideoRecorder() {

        mCamera = getCameraInstance();
        mMediaRecorder = new MediaRecorder();

        // Step 1: Unlock and set camera to MediaRecorder
        mCamera.unlock();
        mMediaRecorder.setCamera(mCamera);//设置调用的摄像头

        // Step 2: Set sources,指定Audio，video来源
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        //视频录制自定义设置
//        CustoMediaRecorder(mMediaRecorder);
        CustoMediaRecorder2(mMediaRecorder);

        // Step 5: Set the preview output
        mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());

        // Step 6: Prepare configured MediaRecorder
        try {
            mMediaRecorder.prepare();
        } catch (IllegalStateException e) {
            Log.d("dove_camera", "IllegalStateException preparing MediaRecorder: " + e.getMessage());
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            Log.d("dove_camera", "IOException preparing MediaRecorder: " + e.getMessage());
            releaseMediaRecorder();
            return false;
        }
        return true;
    }

    private void CustoMediaRecorder(MediaRecorder mMediaRecorder) {
        // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
        //QUALITY_HIGH,QUALITY_QVGA
        mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_QVGA));

        // Step 4: Set output file
        mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO));

//        mMediaRecorder.setVideoEncodingBitRate();
//        mMediaRecorder.setVideoSize();
//        mMediaRecorder.setVideoFrameRate();
//        mMediaRecorder.setAudioEncodingBitRate();
//        mMediaRecorder.setAudioChannels();
//        mMediaRecorder.setAudioSamplingRate();
    }

    private void CustoMediaRecorder2(MediaRecorder mediarecorder) {
        // 指定CamcorderProfile(需要API Level 8以上版本)
        // mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
        //使用CamcorderProfile做配置的话，输出格式，音频编码，视频编码 不要写
        // 设置输出格式和编码格式(针对低于API Level 8版本)
        mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); //设置输出格式，.THREE_GPP为3gp，.MPEG_4为mp4
        mediarecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);//设置声音编码类型 mic
        mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);//设置视频编码类型，一般h263，h264
        mediarecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO));
//        mediarecorder.setVideoSize(640, 480);//设置视频分辨率，设置错误调用start()时会报错，可注释掉在运行程序测试，有时注释掉可以运行
        mediarecorder.setVideoSize(320, 240);
        mediarecorder.setVideoFrameRate(30);//设置视频帧率，可省略
//        mediarecorder.setVideoEncodingBitRate(2 * 1024 * 1024);//提高帧频率，录像模糊，花屏，绿屏可写上调试
        mediarecorder.setVideoEncodingBitRate(900 * 1024);
//        mediarecorder.setPreviewDisplay(surfaceHolder.getSurface()); //设置视频预览
    }

    private String getOutputMediaFile(int mediaTypeVideo) {
        if (MEDIA_TYPE_VIDEO == mediaTypeVideo) {
            String filePath = "/camera_video.3gp";
            File file = new File(ImageTools.getSDPath() + filePath);
            if(file.exists()){
                file.delete();
            }
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ImageTools.getSDPath() + filePath;
        }
        return null;
    }

    /**
     * 检测是否有相机
     *
     * @param context
     * @return
     */
    private boolean checkCameraHardware(Context context) {
        // 支持所有版本
        return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
        //  Android 2.3 (API Level 9) 及以上的
        // return  Camera.getNumberOfCameras() > 0;
    }

    /**
     * 访问摄像头
     *
     * @return
     */
    public static Camera getCameraInstance() {
        Camera c = null;
        try {
            // 在多个摄像头时，默认打开后置摄像头
            c = Camera.open();
            // Android 2.3（API 9之后可指定cameraId摄像头id，可选值为后置（CAMERA_FACING_BACK）/前置（ CAMERA_FACING_FRONT）
            //  c = Camera.open(cameraId);
        } catch (Exception e) {
            // Camera被占用或者设备上没有相机时会崩溃。
        }
        return c;  // returns null if camera is unavailable
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }

    private void releaseMediaRecorder() {
        if (mMediaRecorder != null) {
            mMediaRecorder.reset();   // clear recorder configuration
            mMediaRecorder.release(); // release the recorder object
            mMediaRecorder = null;
            mCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.release();// release the camera for other applications
            mCamera = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
